﻿angular.module('Caltech').controller('procedureItemController', function ($scope, Restangular, $state, $stateParams, $filter, Statuses, Constants, toaster) {
    'use strict';

    $scope.username = Constants.accountInfo.fullName;

    $scope.model = {
        items: [{}, {}, {}, {}, {}, {}, {}, {}],
        createdBy: Constants.accountInfo.id,
        updatedBy: Constants.accountInfo.id
    };

    $scope.getCustomerList = function (name) {
        return Restangular.all('customer').getList({
            name: name
        });
    };

    if ($stateParams.id) {
        Restangular.one('procedure', $stateParams.id).get().then(function (model) {
            $scope.model = model;
            for (var i = model.items.length; i <= 7 ; i++) {
                $scope.model.items.push({});
            };

        });
    } else if ($stateParams.model) {
        // it's copy mode
        $scope.model = JSON.parse($stateParams.model);
    }

    $scope.update = function (model) {
        model.updatedBy = Constants.accountInfo.id;
        model.certifiedBy = Constants.accountInfo.fullName;
        return model.put({ id: model.id }).then(function () {
            $state.forceReload();
        });
    };

    $scope.save = function (model) {
        model.createdBy = Constants.accountInfo.id;
        model.updatedBy = Constants.accountInfo.id;
        model.certifiedBy = Constants.accountInfo.fullName;

        //angular.forEach(model.items, function (item) {
        //    if( item. )
        //    var memberModel = { 'notifierId': member.memberId, 'notifierType': member.notifierType, 'notifierName': member.name };
        //    $scope.model.messageNotifierItems.push(memberModel);
        //});

        return Restangular.all('procedure').post(model).then(function (id) {
            $state.go('procedure-item', { id: id });
        });
    };

    $scope.remove = function (model) {
        return model.remove({ id: model.id }).then(function () {
            history.back();
        });
    };

    $scope.back = function () {
        history.back();
    };

    $scope.updateStandard = function (standard, model) {
        if (!standard) {
            model.standardNo = "";
            model.standardId = "";
        } else if (typeof (standard) === 'object') {
            model.standardNo = standard.standardNo;
            model.standardId = standard.certificateStandardId;
        }
    };

    $scope.getStandardList = function (standardNo) {
        return Restangular.all('standard').getList({
            standardNo: standardNo
        });
    }
});